@echo off
setlocal enabledelayedexpansion

:: Configuration
set SPEC_FILE=.\main-v2.2.1.spec
set SRC_UI_DIR=dist\main-v2.2.1\_internal\UI
set DEST_UI_DIR=dist\main-v2.2.1\UI
set BUILD_LOG=build.log

:: Step 1: Run PyInstaller with logging
echo [INFO] Starting PyInstaller build process...
echo [DEBUG] Command: python.exe -m PyInstaller "%SPEC_FILE%"
call python.exe -m PyInstaller "%SPEC_FILE%" > "%BUILD_LOG%" 2>&1

:: Check PyInstaller result
if %errorlevel% neq 0 (
    echo [ERROR] PyInstaller build failed! Exit code: %errorlevel%
    echo [DEBUG] Check %BUILD_LOG% for details
    exit /b %errorlevel%
)
echo [INFO] PyInstaller build completed successfully

:: Step 2: Verify source UI directory exists
echo [INFO] Verifying source UI directory...
if not exist "%SRC_UI_DIR%" (
    echo [ERROR] Source UI directory not found: %SRC_UI_DIR%
    echo [DEBUG] Possible reasons:
    echo   - Changed output directory structure
    echo   - Build process didn't generate UI files
    echo [DEBUG] Contents of dist\_internal:
    dir /b "dist\_internal" 2>nul || echo [WARNING] dist\_internal directory not found
    exit /b 1
)

:: Step 3: Prepare destination directory
echo [INFO] Preparing destination directory...
if exist "%DEST_UI_DIR%" (
    echo [WARNING] Destination directory already exists. Removing...
    rmdir /s /q "%DEST_UI_DIR%" 2>nul
    if exist "%DEST_UI_DIR%" (
        echo [ERROR] Failed to remove existing directory: %DEST_UI_DIR%
        exit /b 1
    )
)

:: Step 4: Copy UI directory with robocopy
echo [INFO] Copying UI directory...
robocopy "%SRC_UI_DIR%" "%DEST_UI_DIR%" /E /MOVE /NFL /NDL /NJH /NJS >nul

:: Handle robocopy return codes
set "ROBOCOPY_EXITCODE=%errorlevel%"
if %ROBOCOPY_EXITCODE% GEQ 8 (
    echo [ERROR] UI directory copy failed! Robocopy error: %ROBOCOPY_EXITCODE%
    exit /b %ROBOCOPY_EXITCODE%
)

:: Success handling
echo [SUCCESS] UI directory successfully copied to: %DEST_UI_DIR%

:: Final verification
echo [INFO] Performing final verification...
if exist "%DEST_UI_DIR%" (
    set file_count=0
    for /f %%a in ('dir /b /a-d "%DEST_UI_DIR%" 2^>nul ^| find /c /v ""') do set /a file_count=%%a
    if %file_count% GTR 0 (
        echo [INFO] Verification passed: %file_count% files found in destination
    ) else (
        echo [WARNING] Destination directory is empty! Manual check recommended
    )
) else (
    echo [ERROR] Critical failure: Destination directory not created
    exit /b 1
)

endlocal